/**
 * Jest 测试环境设置
 */

// 模拟浏览器环境的一些 API
const { TextEncoder, TextDecoder } = require('util');
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;

// 模拟 localStorage
const localStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  removeItem: jest.fn(),
  clear: jest.fn(),
};
global.localStorage = localStorageMock;

// 模拟 URL API
if (!global.URL) {
  global.URL = class URL {
    constructor(url, base) {
      this.href = url;
      this.origin = '';
      this.protocol = '';
      this.hostname = '';
      this.host = '';
      this.port = '';
      this.pathname = '';
      this.search = '';
      this.hash = '';
      this.searchParams = new URLSearchParams();
    }
  };
}

// 模拟 URLSearchParams
if (!global.URLSearchParams) {
  global.URLSearchParams = class URLSearchParams {
    constructor(search) {
      this.params = new Map();
    }
    
    get(name) {
      return this.params.get(name) || null;
    }
    
    set(name, value) {
      this.params.set(name, value);
    }
    
    delete(name) {
      this.params.delete(name);
    }
    
    has(name) {
      return this.params.has(name);
    }
    
    append(name, value) {
      if (this.params.has(name)) {
        const existing = this.params.get(name);
        this.params.set(name, Array.isArray(existing) ? [...existing, value] : [existing, value]);
      } else {
        this.params.set(name, value);
      }
    }
    
    *[Symbol.iterator]() {
      for (const [key, value] of this.params) {
        if (Array.isArray(value)) {
          for (const v of value) {
            yield [key, v];
          }
        } else {
          yield [key, value];
        }
      }
    }
  };
}

// 模拟 IntersectionObserver
global.IntersectionObserver = class IntersectionObserver {
  constructor(callback, options) {
    this.callback = callback;
    this.options = options;
  }
  
  observe() {}
  unobserve() {}
  disconnect() {}
};

// 模拟 requestAnimationFrame
global.requestAnimationFrame = (callback) => {
  return setTimeout(callback, 16);
};

global.cancelAnimationFrame = (id) => {
  clearTimeout(id);
};

// 模拟 Image 构造函数
global.Image = class {
  constructor() {
    this.onload = null;
    this.onerror = null;
    this.src = '';
    this.width = 0;
    this.height = 0;
    this.naturalWidth = 0;
    this.naturalHeight = 0;
    this.complete = false;
    this.crossOrigin = null;
  }
};